package com.wenchao.quickstart.utils;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * @author zhangwenchao
 */
public class TimeUtil {

    private TimeUtil() {
    }

    /**
     * 获取两个时间差
     *
     * @param time1
     * @param time2
     * @return
     */
    public static long getTimeDiffMinute(long time1, long time2) {
        long diff = Math.abs(time1 - time2);
        return diff / 1000 / 60;
    }

    /**
     * 年月日
     *
     * @return
     */
    public static int[] getDate() {
        int[] array = new int[3];
        Calendar calendar = Calendar.getInstance();
        array[0] = calendar.get(Calendar.YEAR);
        array[1] = calendar.get(Calendar.MONTH) + 1;
        array[2] = calendar.get(Calendar.DAY_OF_MONTH);
        return array;
    }

    /**
     * 年月日
     *
     * @return
     */
    public static int[] getPreDate(int num) {
        int[] array = new int[3];
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, -num); //向前走一天
        array[0] = calendar.get(Calendar.YEAR);
        array[1] = calendar.get(Calendar.MONTH) + 1;
        array[2] = calendar.get(Calendar.DAY_OF_MONTH);
        return array;
    }

    public static String formatTime(Date date, String formatter) {
        SimpleDateFormat sdf = new SimpleDateFormat(formatter);
        return sdf.format(date);
    }

    public static int getCurrentYear() {
        Calendar calendar = Calendar.getInstance();
        return calendar.get(Calendar.YEAR);
    }

    /**
     * MS turn every minute
     *
     * @param duration Millisecond
     * @return Every minute
     */
    public static String timeParse(long duration) {
        String time = "";
        if (duration > 1000) {
            time = timeParseMinute(duration);
        } else {
            long minute = duration / 60000;
            long seconds = duration % 60000;
            long second = Math.round((float) seconds / 1000);
            if (minute < 10) {
                time += "0";
            }
            time += minute + ":";
            if (second < 10) {
                time += "0";
            }
            time += second;
        }
        return time;
    }

    private static SimpleDateFormat msFormat = new SimpleDateFormat("mm:ss");

    /**
     * MS turn every minute
     *
     * @param duration Millisecond
     * @return Every minute
     */
    public static String timeParseMinute(long duration) {
        try {
            return msFormat.format(duration);
        } catch (Exception e) {
            e.printStackTrace();
            return "0:00";
        }
    }
}
